package com.google.gwt.it2tool.server;

import java.io.Serializable;
import java.util.ArrayList;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.gwt.it2tool.client.Factory;
import com.google.gwt.it2tool.client.Production;
import com.google.gwt.it2tool.client.ProductionPrototype;



@PersistenceCapable
public class FactoryJDO implements Serializable{
	
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;	
	
	@Persistent
	private String id;
	
	@Persistent
	private User user;
	
	@Persistent
	private String name;
	
	@Persistent
	private int area;
	
	@Persistent
	@Element(dependent = "true")
	private ArrayList<ProductionJDO> productions = new ArrayList<ProductionJDO>();

	public FactoryJDO(){
	}
	
	public FactoryJDO(Factory factory, User user){
		this.user=user;
		id=factory.getId();
		name=factory.getName();
		
		setProductions(factory.getProductions());
	}
	

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getArea() {
		return area;
	}

	public void setArea(int area) {
		this.area = area;
	}
	
	public String getId(){
		return id;
	}
	
	public void setId(String id){
		this.id=id;
	}
	
	public void addProduction(ProductionJDO prod){
		productions.add(prod);
	}
	
	public void removeProduction(ProductionJDO prod){
		productions.remove(prod);
	}
	
	public int getProductionsCount(){
		return productions.size();
	}
	
	public ArrayList<ProductionJDO> getProductions(){
		return productions;
	}
	
	public void set(Factory fac){
		id = fac.getId();
		name = fac.getName();
		area = fac.getArea();
		
		setProductions(fac.getProductions());
		
	}
	
	private void setProductions(ArrayList<Production> prods){		
		int size = prods.size();
		Production curr;
		DataStorageAdapter dataStorage = new DataStorageAdapter();
		for(int i=0;i<size;i++){
			curr=prods.get(i);
			if (dataStorage.getProduction(curr)==null){
				productions.add(new ProductionJDO(curr.getId(), curr.getName(), curr.getArea(), curr.getProductivity(), curr.getDuration()));
			}else{
				dataStorage.addProduction(curr);
			}
			//Regardless what we do add/update a productionprototype
			dataStorage.storeProductionPrototype(new ProductionPrototype(curr));
		}
	}

	
	public void setUser(User u){
		this.user = u;
	}
}
